#ifndef MYSQL_CONNECTION_POOL_H
#define MYSQL_CONNECTION_POOL_H

#include <mysql/mysql.h>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <string>
#include <thread>

struct DatabaseInfo {
    std::string host;
    int port;
    std::string user;
    std::string password;
    std::string database;
    int maxConnections;
};

class MySQLConnection {
public:
    MySQLConnection(const DatabaseInfo& dbInfo);
    ~MySQLConnection();
    
    bool connect();
    bool isValid() const;
    bool execute(const std::string& sql);
    bool executeQuery(const std::string& sql);
    MYSQL_RES* getResult();
    char* getField(const std::string& fieldName);
    void freeResult();
    
    MYSQL* getMysql() { return mysql; }
    
private:
    MYSQL* mysql;
    MYSQL_RES* result;
    DatabaseInfo dbInfo;
    bool connected;
};

class MySQLConnectionPool {
public:
    static MySQLConnectionPool* getInstance();
    
    bool initPool(const DatabaseInfo& dbInfo, int poolSize);
    std::shared_ptr<MySQLConnection> getConnection();
    void releaseConnection(MySQLConnection* conn);
    void destroyPool();
    
    ~MySQLConnectionPool();
    
private:
    MySQLConnectionPool();
    
    std::queue<MySQLConnection*> connectionPool;
    std::mutex poolMutex;
    std::condition_variable poolCondition;
    DatabaseInfo dbInfo;
    int maxPoolSize;
    bool initialized;
};

#endif // MYSQL_CONNECTION_POOL_H